<template>
  <div>
    <form-marker 
      :isEdit="isEditPage"
      :formData="list" 
      :rulesList="rules"
      :selectList="selectData"
      :eidtList="detailData" 
      v-on:change-rule="getChangeRule"
      v-on:on-confirm="onSaveInfo" 
      v-on:on-cancel="onCancelInfo"></form-marker>
  </div>
</template>
<script>
import FormMarker from '@/components/createPage/createMarker'

export default {
  components: {
    FormMarker
  },
  data () {
    // 自定义验证规则
    let checkGategoryCode = (rule, value, callback) => {
      let reg = /^\d{2}$/
      if (!reg.test(value) && this.pageType === 'new') {
        callback(new Error('分类编码仅支持2位数字，请重新输入'))
      } else if (value && !this.noRepeat && this.pageType === 'new') {
        this.$http.post(`/${this.$const.PREFIX.MAINDATA}/mproductclasses/check`, {itemNo: value}).then((res) => {
          if (res.result) {
            this.noRepeat = res.data
            if (!res.data) { // res.data.data [true]有重复/【false】无重复
              callback(new Error('编码已存在，请重新输入'))
            } else {
              callback()
            }
          } else {
            this.$message.error(res.msg)
          }
        })
      } else {
        callback()
      }
    }
    let checkGategoryName = (rule, value, callback) => {
      if (value && !this.checkGategoryName && this.pageType === 'new') {
        this.$http.post(`/${this.$const.PREFIX.MAINDATA}/mproductclasses/checkname`, {name: value}).then((res) => {
          if (res.result) {
            this.checkGategoryName = res.data // res.data.data [false]有重复/【true】无重复
            if (!res.data) {
              callback(new Error('名称已存在，请重新输入'))
            }
          }
        })
      } else {
        callback()
      }
    }
    // 验证上级分类的函数
    let validateName = (rule, value, callback) => {
      if (!this.changeRule.parentCode && this.changeRule.isHaveTo && !value) {
        callback(new Error('请选择上级分类'))
      } else {
        callback()
      }
    }
    return {
      list: [
        {
          type: 'input',
          label: '分类编码',
          name: '分类编码',
          prop: 'itemNo',
          isDisable: true
        },
        {
          type: 'input',
          label: '分类名称',
          name: '分类名称',
          prop: 'name'
        },
        {
          type: 'select',
          label: '级别',
          name: '级别',
          prop: 'productClass',
          propName: 'productClass',
          optionLabel: 'dicValue',
          optionValue: 'dicValue'
        },
        {
          type: 'select',
          label: '上级分类',
          name: '上级分类',
          prop: 'parentCode',
          propName: 'parentName',
          optionLabel: 'name',
          optionValue: 'code'
          // ref: 'parentCategory'
        }
      ],
      rules: {
        itemNo: [
          { max: 32, message: '长度不可超过32个字符', trigger: 'change' },
          { required: true, message: '分类编码不允许为空', trigger: 'change' },
          { validator: checkGategoryCode, trigger: 'change' }
        ],
        name: [
          { max: 64, message: '长度不可超过64个字符', trigger: 'blur' },
          { required: true, message: '分类名称不允许为空', trigger: 'blur' },
          { validator: checkGategoryName, trigger: 'change' }
        ],
        productClass: [{ required: true, message: '级别不允许为空', trigger: 'change' }],
        parentCode: [{ validator: validateName, trigger: 'change' }]
      },
      selectData: {},
      detailData: {},
      noRepeat: false,
      noRepeatName: false,
      changeRule: {},
      isEditPage: false
    }
  },
  mounted () {
    this.pageType = this.$route.params.id
    this.init()
    this.getParentSelect()
    this.getClassSelect()
    this.getCategoryDetail()
  },
  methods: {
    init () {
      let curProductClass = this.$localStorage.get(this.$const.SAVEWEBINFO.GRADE)
      if (curProductClass) {
        this.selectData.productClass = JSON.parse(JSON.stringify(curProductClass))
      } else {
        this.getClassSelect()
      }
    },
    // 获取编辑详情数据
    async getCategoryDetail () {
      if (this.pageType !== 'new') {
        let {data} = await this.$http.post(`/${this.$const.PREFIX.MAINDATA}/mproductclasses/getOne`, {id: this.pageType})
        this.detailData = data
        this.detailData.parentCode = data.parentCode === '-1' ? '' : data.parentCode
        this.isEditPage = true
      }
    },
    // 获取级别下拉列表数据
    async getClassSelect () {
      let {data} = await this.$http.post(`/${this.$const.PREFIX.AUTHORITY}/dictionary/findDictionaryByType`, {type: 'product_class'})
      this.selectData.productClass = data || []
      this.selectData.productClass = this.selectData.productClass.map((val) => {
        val.dicValue = val.dicValue === '一级' ? '大分类' : '小分类'
        return val
      })
      this.selectData = JSON.parse(JSON.stringify(this.selectData))
      this.$localStorage.set(this.$const.SAVEWEBINFO.GRADE, this.selectData.productClass)
    },
    // 获取上级分类下拉列表数据
    async getParentSelect () {
      let {data} = await this.$http.post(`/${this.$const.PREFIX.MAINDATA}/mproductclasses/listParentClasses`, {itemType: 0})
      this.selectData.parentCode = data
      this.selectData = JSON.parse(JSON.stringify(this.selectData))
    },
    // 分类 与上级区域 级联验证
    getChangeRule (val) {
      this.changeRule = val
    },
    // 接口保存新建信息
    onSaveInfo (val) {
      let url = this.pageType === 'new' ? `/${this.$const.PREFIX.MAINDATA}/mproductclasses/add` : `/${this.$const.PREFIX.MAINDATA}/mproductclasses/update`
      let obj = val
      obj.itemType = '0'
      this.$http.post(url, obj).then((res) => {
        if (res.result) {
          if (res.data === 'false') {
            this.$message.error(res.msg)
          } else {
            this.$message.success('操作成功')
            this.$router.push({name: 'goodsCategory'})
          }
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    onCancelInfo () {
      this.$router.push({name: 'goodsCategory'})
    }
  }
}
</script>
<style lang="scss" scoped>

</style>


